﻿$(document).ready(function () {

    //Global

    var $last;
    prepareScreen();

    //--- BEHAVIOURS ---

    // Form submition
    $("form[id*='Primary']").submit(function () {

        //Set destination
        var $mainComplaint = $("input:radio[name = complaints_complaint]:checked").val();
        $(this).attr("action", "includes/mains/Main-" + $mainComplaint + ".php");

        if ($last == "#submit") {
            $("form").attr('action', 'includes/output/Output.php');
        }
    });

    $("form[id*='Main']").submit(function () {

        if (($("input[name='none_additional']:checked").val() == "yes")) {
            //Set destination
            $(this).attr("action", "../../index.php");
        }
        else {
            $(this).attr("action", "../sections/SelectOutput.php");
        }

    });

    // Back / Forward buttons
    $(".nav li a[href='#']").click(function () {

        $whereWeAre = '#' + $(this).parent().closest("div").attr('id');
        $whereWeGo = $('.nav li a[name="' + $whereWeAre + '"]').parent();
        if ($(this).attr('name') == 'back') {
            if ($whereWeAre == "#personal_details") {
                $whereWeGo = "#landing_page";
            }
            else if ($whereWeAre == "#Primary_complaint") {
                $whereWeGo = $last;
            }
            else {
                $whereWeGo = $whereWeGo.prev().children(':first').attr('name');
            }
            if ($whereWeGo == "#landing_page") {
                $("#rec_id").removeAttr('disabled');
                $("#first_id").attr("disabled", "disabled");
                $('#disclaimer').hide();

            }
        }
        else if ($whereWeAre == "#only_id") {
            $whereWeGo = "#Primary_complaint";
        }
        else {
            $whereWeGo = $whereWeGo.next().children(':first').attr('name');
        }

        $(this).attr("href", $whereWeGo);

        updateConent();
        return false;

    });

    // First page navigation

    $(".nav-ten a").click(function () {
        $('#server_reply').css("color", "green");
        $('#server_reply').html("בודק נתונים");
        var $user = $("#rec_id").val();
        var $pass = $("#rec_pass").val();
        if (!$user) {
            $('#server_reply').css("color", "red");
            $('#server_reply').html("נא להכניס ת.ז או קוד משתמש");
        }
        else {
            var $request = $.ajax({
                type: "POST",
                url: "database/login.php",
                data: { pass: $pass, user: $user },
                success: function ($request) {
                    if ($request == true) {
                        $whereWeAre = '#landing_page';
                        $whereWeGo = "#Primary_complaint";
                        $('#server_reply').html("");
                        $("#rec_id").attr("required", "required");
                        $("#first_id").attr('disabled', 'disabled');
                        updateConent();
                    }
                    else {
                        $('#server_reply').css("color", "red");
                        $('#server_reply').html("המשתמש אינו קיים במערכת");
                    };
                }
            });
        }
    });
    $(".nav-eleven a").click(function () {
        $whereWeAre = '#landing_page';
        $whereWeGo = "#personal_details";
        $("#first_id").removeAttr('disabled');
        $("#rec_id").attr('disabled', 'disabled');
        $('#disclaimer').show();
        updateConent();
    });
    /*
    $(".nav-ten a").click(function () {
    $whereWeAre = '#landing_page';
    if (($("input[name='users_visit']:checked").val() == "recurring")) {
    $whereWeGo = "#only_id";
    $("#rec_id").attr("required", "required");
    $("#first_id").attr('disabled', 'disabled');
    }
    else {
    $whereWeGo = "#personal_details";
    $("#first_id").removeAttr('disabled');
    $("#rec_id").removeAttr('required');
    }
    $(this).attr("href", $whereWeGo);

    updateConent();
    return false;
    });
    */

    $("#skip").click(function () {
        $whereWeAre = '#' + $(this).parent().parent().siblings("div :visible").attr('id');
        $whereWeGo = "#Primary_complaint";
        updateConent();
    });

    $("#selectOutput input").click(function () {
        window.location.href = "../output/" + $(this).val() + "?complaint_id=" + $("#complaintID").val();
        //updateConent();
    });

    // Buttons that appear only after condition met
    $(".condButton").click(function () {
        $(this).siblings(".nav").show();
    });

    //Check if content update is needed
    function prepareScreen() {

        //if returened from a complaint page
        var $referrer = document.referrer;
        if ($referrer.indexOf("Main") != -1) {
            //go straight to the main complaint section
            $(".nav-zero a").removeClass("current");
            $("#landing_page").addClass("hide");
            $("#Primary_complaint").removeClass("hide");
            $("#Primary_complaint h3").text("אילו עוד תסמינים נוספים ישנם?");
            //replace back button with submit
            $("#final").text("סיים");
            $("#final").click(function () {
                $whereWeGo = "#please_wait";
                $whereWeAre = "#Primary_complaint";
                updateConent();
                $last = "#submit";
                $(this).closest("form").submit();
            });

            $('#tabs_wrap li a[name="#landing_page"]').parent().hide();
            $('#tabs_wrap li a[name="#additions"]').parent().removeClass('hide');
            $(".nav-eleven a").addClass("current");
        }

        $("#Primary_details").children("div .hide").append('<ul class="nav"><li><a href="#" name="back" hidden="false">חזור</a></li><li><a href="#" name="go"hidden="false">המשך</a></li></ul>');

        //Placing the hidden elements on screen (and hiding them)
        $(".hide").css({
            "position": "relative ",
            "top": 0,
            "left": 0,
            "display": "none"
        });

    };

    //Internal function - replace contect on screen
    function updateConent() {

        //replace relevant content
        var $targetPageID = $whereWeGo;
        var $currentPageID = $whereWeAre;
        if ($targetPageID != $currentPageID) {
            $($currentPageID).fadeOut(100, 'linear', function () {
                $($targetPageID).fadeIn(200, 'linear');
                $("#tabs_wrap li a").removeClass("current");
                $('#tabs_wrap li a[name="' + $currentPageID + '"]').parent().hide();
                $('#tabs_wrap li a[name="' + $targetPageID + '"]').parent().show();
                $('#tabs_wrap li a[name="' + $targetPageID + '"]').addClass("current");
            });
            $last = $whereWeAre;
        }
    };

    //****CSS Styling**** 

    //For sensitivities
    $(".redText").each(function () {
        if ($(this).text().indexOf("כן") >= 0) {
            $(this).css('color', 'red');
        }
    });

    //For disease list parent relevance
    $(".backgroundDiseases input").each(function () {
        attachName($(this));
        $(this).parent().append('<div class="sicko" hidden><label class="radiolabel">?כמה שבועות ידוע לך על המחלה</label><input type="text" size="2" name="background_timeill" id="timeill1" value="0"/><input type="checkbox" name="background_timeUnits" id="knowunits1" value="years" disabled/><label class="" for="knowunits1">שנים</label><input type="checkbox" name="background_timeUnits" id="knowunits2" value="months" disabled/><label class="" for="knowunits2">חודשים</label><section hidden><input type="checkbox" name="background_treated" id="treated1" value="1"/><label class="radiolabel">?האם מטופל</label><br/></section></div>');
    });

    //Click functions
    $(".backgroundDiseases input").click(function () {
        $me = $(this);
        $me.siblings(".sicko").toggle();
    });

    $("input[name='background_timeUnits']").change(function () {
        $me = $(this);
        $me.siblings('section').toggle();
        $pa = $me.parent().siblings("input");
        $oldVal = $pa.val();
        $length = $oldVal.length;
        $index = $oldVal.indexOf("חודשים");
        if ($index == -1) {
            $index = $oldVal.indexOf("שנים");
        }
        if ($index == -1) {
            if ($me.val() == 'years') {
                $units = "שנים";
            }
            else {
                $units = "חודשים";
            }
            $newVal = $oldVal + $units;
            $pa.val($newVal);
        }
    });

    $("input[name='background_timeill']").keyup(function () {
        $me = $(this);
        $pa = $me.parent().siblings("input");
        $oldVal = $pa.val();
        $length = $oldVal.length;
        $index = $oldVal.indexOf("מזה");
        if ($index != -1) {
            $newVal = $oldVal.substring(0, $index - 1);
        }
        else {
            $newVal = $oldVal;
        }
        $newVal += " מזה " + $me.val() + " ";
        $pa.val($newVal);
        $me.siblings("input").removeAttr('disabled');
    });

    $("input[name='background_treated']").click(function () {
        $me = $(this);
        $grandpa = $me.parent().parent().siblings("input");
        $oldVal = $grandpa.val();
        if ($me.is(':checked')) {
            $newVal = $oldVal + ": מטופל/ת ";
        }
        else {
            $length = $oldVal.length;
            $newVal = $oldVal.substring(0, $length - 10);
        }
        $grandpa.val($newVal);
    });

    //For deathCause list parent relevance
    $(".deathCauses input").each(function () {
        attachName($(this));
    });

    //Attaches name to the input element
    function attachName($elem) {
        $name = $elem.closest(".backgroundDiseases").attr('id');
        $elem.attr("name", $name);
    };

    $("#rec_id").focus();
});